package com.ruoyi.rsikManage.service.Impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.GenericMethodsService;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.electronicFence.domain.TEfAreaApe;
import com.ruoyi.electronicFence.domain.TEfFenceArea;
import com.ruoyi.electronicFence.mapper.TEfAreaApeMapper;
import com.ruoyi.electronicFence.mapper.TEfFenceAreaMapper;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.rsikManage.domain.*;
import com.ruoyi.rsikManage.domain.common.StatisticsRequest;
import com.ruoyi.rsikManage.domain.vo.AlarmsVo;
import com.ruoyi.rsikManage.domain.vo.BroadCastRequestVo;
import com.ruoyi.rsikManage.mapper.*;
import com.ruoyi.rsikManage.service.CustomConfigurationService;
import com.ruoyi.rsikManage.service.ITUnitConfigService;
import com.ruoyi.rsikManage.service.JyService;
import com.ruoyi.rsikManage.service.StatisticalAnalysisService;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wxx
 * @description
 * @date 2023/9/7 17:16
 * @motto
 */
@Service
public class StatisticalAnalysisServiceImpl implements StatisticalAnalysisService {
    @Value("${broadcast.type}")
    private Integer BROADCAST_TYPE;
    @Autowired
    public StatisticalAnalysisMapper statisticalAnalysisMapper;

    @Autowired
    public ReportApprovalMapper reportApprovalMapper;

    @Autowired
    public AlarmEventMapper alarmEventMapper;

    @Autowired
    public CustomConfigurationService customConfigurationService;

    @Autowired
    public BroadcastMapper broadcastMapper;

    @Autowired
    public TVideoMessageQueueMapper tVideoMessageQueueMapper;

    @Autowired
    public JyService jyService;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private GenericMethodsService genericMethodsService;

    @Value("${jy.switch}")
    private String JY_SWITCH;


    @Value("${jy.name_prefix}")
    private String namePrefix;
    @Value("${jy.name_suffix}")
    private String nameSuffix;

    @Value("${system.ip}")
    private String SERVER_IP;
    @Value("${system.web_port}")
    private String WEB_PORT;


    @Autowired
    ServletContext servletContext;
    @Autowired
    TEfFenceAreaMapper tEfFenceAreaMapper;
    @Autowired
    TEfAreaApeMapper tEfAreaApeMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ITUnitConfigService iTUnitConfigService;

    @Override
    public List<AlarmEvent> selectAlarmAlgoName() {

        List<AlarmEvent> alarmEvents = statisticalAnalysisMapper.selectAlarmAlgoName();
        return alarmEvents;
    }

    @Override
    public List<AlarmEvent> selectAlarmAlgoNameGroup(AlarmEventRequest alarmEventRequest) {

        List<AlarmEvent> alarmEvents = statisticalAnalysisMapper.selectAlarmAlgoNameGroup(alarmEventRequest);
        return alarmEvents;
    }

    @Override
    public List<AlarmEvent> selectAlarmOrgName() {

        List<AlarmEvent> alarmEvents = statisticalAnalysisMapper.selectAlarmOrgName();
        return alarmEvents;
    }

    @Override
    public List<AlarmEvent> selectAlarmApeName(AlarmEventRequest alarmEventRequest) {

        List<AlarmEvent> alarmEvents = statisticalAnalysisMapper.selectAlarmApeName( alarmEventRequest);
        return alarmEvents;
    }

    @Override
    public List<AlarmEvent> selectAllAlarmInfo(AlarmEventRequest alarmEventRequest) {

        // 获取昨天现在的时间字符串（年月日 时分秒）
        LocalDateTime yesterdayNow = LocalDateTime.now().minusDays(1);
        String yesterdayNowString = yesterdayNow.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println("昨天现在的时间：" + yesterdayNowString);

        // 获取今天现在的时间字符串（年月日 时分秒）
        LocalDateTime todayNow = LocalDateTime.now();
        String todayNowString = todayNow.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println("今天现在的时间：" + todayNowString);


        if (alarmEventRequest.getStartTime() == null) {
            alarmEventRequest.setStartTime("2023-05-01 00:00:00");
        }

        if (alarmEventRequest.getEndTime() == null) {
            alarmEventRequest.setEndTime(todayNowString);
        }


        if (alarmEventRequest.getSort() == null) {
            alarmEventRequest.setSort("DESC");
        }

        int pageNum = alarmEventRequest.getPageNum();

        int pageSize = alarmEventRequest.getPageSize();

        alarmEventRequest.setPageSize(null);
        alarmEventRequest.setPageNum(null);

        // 获取开始时间戳
        long startTime = System.currentTimeMillis();
        // 获取结束时间戳
        // 1.查询报警列表
        List<AlarmEvent> AllAlarmmaps = statisticalAnalysisMapper.selectAllAlarmInfo(alarmEventRequest);
        long endTime = System.currentTimeMillis();
        //
        // 打印查询时间
        long queryTime = endTime - startTime;
        System.out.println("查询时间：statisticalAnalysisMapper.selectAllAlarmInfo" + queryTime + "毫秒");
        // 2.查询报备信息
        List<ReportApproval> AllAlarmFilterList = statisticalAnalysisMapper.selectAllAlarmFilterList(alarmEventRequest);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (AlarmEvent alarm : AllAlarmmaps) {
            if(AllAlarmFilterList.size()>0){
                for (ReportApproval filter : AllAlarmFilterList) {
                    if (alarm.getDeviceId().equals(filter.getApeId())) {
                        LocalDateTime alarmTime = alarm.getAlarmTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                        LocalDateTime startDate = filter.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
                        LocalDateTime endDate = filter.getEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();

                        if (isBetween(alarmTime, startDate, endDate)) {
                            alarm.setEventFlag("1");
                        }
                    }
                }
            }

        }


        if ("0".equals(alarmEventRequest.getFilter())) {
            List<AlarmEvent> filteredEvents = AllAlarmmaps.stream()
                    .filter(event -> !"2".equals(event.getApprove()))
                    .collect(Collectors.toList());

            AllAlarmmaps.clear(); // 清空原始列表

            AllAlarmmaps.addAll(filteredEvents);


            List<AlarmEvent> filteredEvents2 = AllAlarmmaps.stream()
                    .filter(event -> !"1".equals(event.getEventFlag()))
                    .collect(Collectors.toList());

            AllAlarmmaps.clear(); // 清空原始列表

            AllAlarmmaps.addAll(filteredEvents2);

        }


        if ("2".equals(alarmEventRequest.getFilter())) {
            List<AlarmEvent> filteredEvents = AllAlarmmaps.stream()
                    .filter(event -> "1".equals(event.getEventFlag()) || "2".equals(event.getApprove()))
                    .collect(Collectors.toList());

            AllAlarmmaps.clear(); // 清空原始列表

            AllAlarmmaps.addAll(filteredEvents);
        }
        long endTime2 = System.currentTimeMillis();
        //
        // 打印查询时间
        long queryTime2 = endTime2 - startTime;
        System.out.println("查询时间：过滤" + queryTime2 + "毫秒");

        //  AllAlarmFilterList 遍历出 和 startDate 以及 endDate 和 AllAlarmmaps 中deviceId 和 alarmTime时间进行对比 当 apeId和deviceId 相同时 查看alarmTime是否在startDate 和 endDate之间 如果在 则 给AllAlarmmaps的对应map中isReport赋值为"1"

        int startIndex = (pageNum - 1) * pageSize;

        if (startIndex >= AllAlarmmaps.size()) {
            return Collections.emptyList(); // 返回空列表表示不存在该页
        }

        int endIndex = Math.min(startIndex + pageSize, AllAlarmmaps.size());

        List<AlarmEvent> alarmEvents = AllAlarmmaps.subList(startIndex, endIndex);
        /*
        List<AlarmEvent> alarmEvents 拿出里面所有的 pictureUrl 放入 List<String> a中 进行 jyService.picAddrTrans(a)的方法调用 拿到返回值的 data数组里面的第一个值 再放回pictureUrl中 实现路径转换
         */

        //List<AlarmEvent>

        //

        List<Long> urlList = new ArrayList<>();
        List<String> urlListString = new ArrayList<>();
//
//        }



        // 将 alarmEvents 中的所有 pictureUrl 添加到 a 中
        for (AlarmEvent event : AllAlarmmaps) {
            urlList.add(event.getIdId());
        }
        alarmEventRequest.setIds(urlList);
        List<AlarmEvent> alarmEvents1 = statisticalAnalysisMapper.selectAllAlarmInfoBase64(alarmEventRequest);
//
        for (AlarmEvent event : alarmEvents1) {
            urlListString.add(event.getPictureUrl());
        }
        if("true".equals(JY_SWITCH)){
//            String s = jyService.picAddrTrans(urlListString);
//            System.out.println(s);
//            Map<String, Object> maps = JSON.parseObject(s);
//            List<String> urlList2 = (List<String>) maps.get("data");
            //遍历 List<AlarmEvent> alarmEvents 和 List<String> urlList2 依次按照数组索引 让 urlList2 的内容 代替 alarmEvents中的 pictureUrl 字段
            {
                for (int i = 0; i < alarmEvents1.size(); i++) {
                    List<String> urlListString2 = new ArrayList<>();
                    String s="";
                    urlListString2.add(alarmEvents1.get(i).getPictureUrl());
                    if(urlListString2.get(0)==null){
                        s="";
                    }else {
                        try {
                            s = jyService.picAddrTrans(urlListString2);
                        } catch (Exception e) {
                            s = "";
                        }

                    }


                    System.out.println(s);
                    Map<String, Object> maps = JSON.parseObject(s);
                    if (maps==null||maps.get("data")==null){

                        AlarmEvent event = alarmEvents1.get(i);
                        event.setPictureUrl("");
                    }else {
                        List<String> urlList2 = (List<String>) maps.get("data");
                        AlarmEvent event = alarmEvents1.get(i);
                        String newPictureUrl = urlList2.get(0);
                        System.out.println(newPictureUrl);
                        event.setPictureUrl(newPictureUrl);
                    }



                }
            }
            System.out.println(alarmEvents1.get(0).getPictureUrl());
        }


        return alarmEvents1;


    }

    /**
     * CN：查询所有报警信息并补充视频路径信息（版本2）。
     * EN：Selects all alarm information and supplements video path information (Version 2).
     *
     * @param alarmEventRequest
     * CN：报警事件请求对象，包含查询参数。
     * EN：An alarm event request object containing query parameters.
     *
     * @return
     * CN：包含完整视频路径信息的报警事件列表。
     * EN：A list of alarm events with complete video path information.
     */
    public List<AlarmEvent> selectAllAlarmInfoV2(AlarmEventRequest alarmEventRequest) {
        // 判断是否有排序，默认为降序
        if (StringUtils.isEmpty(alarmEventRequest.getSort())) {
            alarmEventRequest.setSort("DESC");
        }

        // 查询所有报警信息
        List<AlarmEvent> alarmEvents = statisticalAnalysisMapper.selectAllAlarmInfoV2(alarmEventRequest);
        Map<Long, SysDept> deptMap = genericMethodsService.getDeptMap();

        // 遍历 alarmEvents 列表，根据 unitCode 匹配 deptName 并赋值给 unitName
        for (AlarmEvent alarmEvent : alarmEvents) {
            SysDept dept = deptMap.get(alarmEvent.getUnitCode());
            if (dept != null) {
                alarmEvent.setUnitName(dept.getDeptName());
            }
        }

        // 补全煤矿编码对应的煤矿名称

        // 补全报警事件列表中的识别视频路径信息
        return updateAlarmEventsWithVideoPaths(alarmEvents);
    }

    /**
     * CN：查询所有报警信息并补充视频路径信息（版本2）。
     * EN：Selects all alarm information and supplements video path information (Version 2).
     *
     * @param alarmEventRequest
     * CN：报警事件请求对象，包含查询参数。
     * EN：An alarm event request object containing query parameters.
     *
     * @return
     * CN：包含完整视频路径信息的报警事件列表。
     * EN：A list of alarm events with complete video path information.
     */
    public List<AlarmsVo> selectAlarms(AlarmEventRequest alarmEventRequest) {
        // 判断是否有排序，默认为降序
        if (StringUtils.isEmpty(alarmEventRequest.getSort())) {
            alarmEventRequest.setSort("DESC");
        }

        // 查询所有报警信息
        List<AlarmsVo> alarmEvents = statisticalAnalysisMapper.selectAlarms(alarmEventRequest);
        Map<Long, SysDept> deptMap = genericMethodsService.getDeptMap();

        // 遍历 alarmEvents 列表，根据 unitCode 匹配 deptName 并赋值给 unitName
        for (AlarmsVo alarmEvent : alarmEvents) {
            SysDept dept = deptMap.get(alarmEvent.getUnitCode());
            if (dept != null) {
                alarmEvent.setUnitName(dept.getDeptName());
            }
        }

        // 补全煤矿编码对应的煤矿名称

        // 补全报警事件列表中的识别视频路径信息
        return alarmEvents;
    }

    /**
     * CN：更新报警事件列表中的视频路径信息。
     * EN：Updates the video paths in a list of alarm events.
     *
     * @param alarmEvents
     * CN：报警事件列表。
     * EN：A list of alarm events.
     *
     * @return
     * CN：更新后的报警事件列表。
     * EN：The updated list of alarm events.
     */
    public List<AlarmEvent> updateAlarmEventsWithVideoPaths(List<AlarmEvent> alarmEvents) {
        // 创建一个 TVideoMessageQueue 对象，用于设置查询参数
        TVideoMessageQueue tVideoMessageQueue = new TVideoMessageQueue();
        tVideoMessageQueue.setMessageStatus("1");

        // 先收集所有的 alarmId
        List<Long> alarmIds = new ArrayList<>();
        for (AlarmEvent alarm : alarmEvents) {
            alarmIds.add(alarm.getIdId());
        }

        // 设置批量查询所需的 alarmIds
        tVideoMessageQueue.setAlarmIds(alarmIds);

        // 批量查询所有需要的 TVideoMessageQueue 记录
        List<TVideoMessageQueue> tVideoMessageQueues = tVideoMessageQueueMapper.selectTVideoMessageQueueList(tVideoMessageQueue);

        // 创建一个 map 来存储 alarmId 到 videoNewProxyPath 的映射
        Map<Long, String> alarmIdToVideoPathMap = new HashMap<>();
        // 将结果放入 map 中
        for (TVideoMessageQueue queue : tVideoMessageQueues) {
            if (queue.getVideoNewProxyPath() != null) {
                alarmIdToVideoPathMap.put(queue.getAlarmId(), queue.getVideoNewProxyPath());
            }
        }

        // 更新每个 AlarmEvent 的 videoNewProxyPath 字段
        for (AlarmEvent alarm : alarmEvents) {
            Long alarmId = alarm.getIdId();
            String videoNewProxyPath = alarmIdToVideoPathMap.get(alarmId);
            if (videoNewProxyPath != null) {
                alarm.setVideoNewProxyPath(videoNewProxyPath);
            }
        }
        return alarmEvents;
    }

    public List<AlarmEvent> selectAllAlarmInfoEF(AlarmEventRequest alarmEventRequest) {
        // 判断是否有排序，默认为降序
        if (StringUtils.isEmpty(alarmEventRequest.getSort())) {
            alarmEventRequest.setSort("DESC");
        }

        // 判断是否进行区域选择
        TEfFenceArea tEfFenceArea = new TEfFenceArea();
        List<TEfFenceArea> tEfFenceAreas;
        if (alarmEventRequest.getAreaIds() != null && alarmEventRequest.getAreaIds().size() > 0) {
            List<Long> areaIds = alarmEventRequest.getAreaIds();
            tEfFenceArea.setIds(areaIds);
            tEfFenceAreas = tEfFenceAreaMapper.selectTEfFenceAreaDetailsList(tEfFenceArea);

        }else {
            tEfFenceAreas = tEfFenceAreaMapper.selectTEfFenceAreaDetailsList(tEfFenceArea);
        }



            List<String> apeIds = new ArrayList<>();
            // 处理空指针异常，确保tEfFenceAreas不为空
            if (tEfFenceAreas != null) {
                for (TEfFenceArea Area : tEfFenceAreas) {
                    List<TEfAreaApe> tEfAreaApes = Area.getTEfAreaApes();
                    // 处理空指针异常，确保tEfAreaApes不为空
                    if (tEfAreaApes != null) {
                        for (TEfAreaApe ape : tEfAreaApes) {
                            apeIds.add(ape.getApeId());
                        }
                    }
                }
            }
            alarmEventRequest.setApeIds(apeIds);

        List<AlarmEvent> alarmEvents = statisticalAnalysisMapper.selectAllAlarmInfoV2(alarmEventRequest);

        for (AlarmEvent alarmEvent : alarmEvents) {
            TEfAreaApe tEfAreaApe = new TEfAreaApe();
            tEfAreaApe.setApeId(alarmEvent.getDeviceId());

            List<TEfAreaApe> tEfAreaApes = tEfAreaApeMapper.selectTEfAreaApeList(tEfAreaApe);

            if (tEfAreaApes != null && !tEfAreaApes.isEmpty()) {
                TEfAreaApe firstAreaApe = tEfAreaApes.get(0);
                if (firstAreaApe != null) {
                    alarmEvent.setAreaName(firstAreaApe.getAreaName());
                    alarmEvent.setAreaId(firstAreaApe.getAreaId());
                } else {
                    // 处理第一个区域设备为空的情况
                    // 可以设置默认值或记录日志
                    alarmEvent.setAreaName(null);
                    alarmEvent.setAreaId(null);
                }
            } else {
                // 处理区域设备列表为空的情况
                // 可以设置默认值或记录日志
                alarmEvent.setAreaName(null);
                alarmEvent.setAreaId(null);
            }
        }

        return alarmEvents;
    }
    @Override
    public String uploadFile(MultipartFile file, String type) {
        if (file.isEmpty()) {
            return "请选择要上传的文件";
        }

        try {
            // 获取文件的原始名称
            String originalFileName = file.getOriginalFilename();
            String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
            UUID uuid = UUID.randomUUID();
            String fileName = uuid.toString() + fileExtension;
            String storagePath = "";

            if (type.equals("image")) {
                storagePath = "D:/zdzh/var/image/";
            } else {
                storagePath = "D:/zdzh/var/video/";
            }

            // 指定存储目录

            // 创建目标文件对象
            File destFile = new File(storagePath + fileName);

            // 检查目标目录是否存在，不存在则创建
            File destDirectory = destFile.getParentFile();
            if (!destDirectory.exists()) {
                destDirectory.mkdirs();
            }

            // 将文件保存到目标位置
            FileOutputStream fos = new FileOutputStream(destFile);
            fos.write(file.getBytes());
            fos.close();

            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败";
        }
    }





    @Override
    public List<AlarmEvent> selectAlarmById(AlarmEventRequest alarmEventRequest) {
        List<AlarmEvent> AllAlarmmaps = statisticalAnalysisMapper.selectAllAlarmById(alarmEventRequest);

        return AllAlarmmaps;
    }

    @Override
    public int updateAlarmInfo(AlarmEvent alarmEvent) {

        int row = statisticalAnalysisMapper.updateAlarmInfo(alarmEvent);
        return row;
    }

    @Override
    public int batchUpdateAlarmInfo(List<AlarmEvent> alarmEvents) {

        int row = statisticalAnalysisMapper.batchUpdateAlarmInfo(alarmEvents);
        return row;
    }

    @Override
    public Map<String,Object> selectAlarmIndex(AlarmEventRequest alarmEventRequest) {

        Map<String, Object> result = new HashMap<>();
        //1.获取报警列表
        List<AlarmEvent> alarmEvents = statisticalAnalysisMapper.selectAllAlarmInfoV2(alarmEventRequest);


        //2.按不同的报警事件名称 将list分类
        Map<String, List<AlarmEvent>> alarmMap2 = alarmEvents.stream()
                .collect(Collectors.groupingBy(AlarmEvent::getAlarmTypeName));

        //2.按不同的报警处理状态名称 将list分类
        Map<String, List<AlarmEvent>> alarmMap = alarmEvents.stream()
                .collect(Collectors.groupingBy(AlarmEvent::getHandelStatus));

        //List<AlarmEvent> alarmEvents 先按不同的报警处理状态名称 handelStatus将list分类 再按不同的报警等级 alarmLevels分类

        // 按不同的报警处理状态名称分类
        Map<String, List<AlarmEvent>> byHandelStatus = alarmEvents.stream()
                .collect(Collectors.groupingBy(AlarmEvent::getHandelStatus));

        // 对每个分类再按不同的报警等级分类
        Map<String, Map<String, List<AlarmEvent>>> byHandleAndAlarmLevel =
                byHandelStatus.entrySet().stream()
                        .collect(Collectors.toMap(
                                Map.Entry::getKey,
                                entry -> entry.getValue().stream()
                                        .collect(Collectors.groupingBy(AlarmEvent::getAlarmLevel))
                        ));






        //3.筛选出不同分类下 不同报警等级的次数
        Map<String, Map<String, Long>> alarmLevelCountMap = new HashMap<>();

        for (Map.Entry<String, List<AlarmEvent>> entry : alarmMap.entrySet()) {
            String categoryName = entry.getKey();
            List<AlarmEvent> events = entry.getValue();

            Map<String, Long> levelCountMap = new HashMap<>();
            String[] alarmLevels = {"5", "4", "3"};

            for (String level : alarmLevels) {
                levelCountMap.put(level, 0L);
            }

            for (AlarmEvent event : events) {
                String alarmLevel = event.getAlarmLevel();
                if (levelCountMap.containsKey(alarmLevel)) {
                    levelCountMap.put(alarmLevel, levelCountMap.get(alarmLevel) + 1);
                }
            }

            alarmLevelCountMap.put(categoryName, levelCountMap);
        }
        //4.查询监控点个数
        List<MonitorPoint> monitorPoints = statisticalAnalysisMapper.selectMonitorPointCount(alarmEventRequest);

        //5.获取报警总数
        int alarmCount = alarmEvents.size();
        //3.获取监控点总数
        int monitorPointCount = monitorPoints.size();
        long l4=0;
        long l8=0;

        if(alarmLevelCountMap.get("1")!=null){

            long l = alarmLevelCountMap.get("1").get("5").longValue();
            long l2 = alarmLevelCountMap.get("1").get("4").longValue();
            long l3= alarmLevelCountMap.get("1").get("3").longValue();
            l4=l+l2+l3;
;;;        }
        if(alarmLevelCountMap.get("3")!=null){

            long l = alarmLevelCountMap.get("3").get("5").longValue();
            long l2 = alarmLevelCountMap.get("3").get("4").longValue();
            long l3= alarmLevelCountMap.get("3").get("3").longValue();
            l8=l+l2+l3
            ;;;        }

        result.put("conut1",l4);
        result.put("conut2",l8);
        result.put("alarmLevelSort",alarmLevelCountMap);
//        result.put("list",alarmMap);
        result.put("list",byHandleAndAlarmLevel);
        result.put("alarmCount",alarmCount);
        result.put("monitorPointCount",monitorPointCount);

        //https://console.huaweicloud.com/rds/?agencyId=ca5695528caa4036b7e6faf7dada890a&region=cn-north-4&locale=zh-cn#/rds/management/connectTab/838d3ccc2080453c8edd25a2815b4678in01


        return result;

    }

    @Override
    public Map<String,Object> selectAlarmIndexForUnitCodes(AlarmEventRequest alarmEventRequest) {

        Map<String, Object> result = new HashMap<>();
        //1.获取报警列表
        List<AlarmEvent> alarmEvents = statisticalAnalysisMapper.selectAllAlarmInfoV2ForUnitCodes(alarmEventRequest);


        //2.按不同的报警事件名称 将list分类
        Map<String, List<AlarmEvent>> alarmMap2 = alarmEvents.stream()
                .collect(Collectors.groupingBy(AlarmEvent::getAlarmTypeName));

        //2.按不同的报警处理状态名称 将list分类
        Map<String, List<AlarmEvent>> alarmMap = alarmEvents.stream()
                .collect(Collectors.groupingBy(AlarmEvent::getHandelStatus));

        //List<AlarmEvent> alarmEvents 先按不同的报警处理状态名称 handelStatus将list分类 再按不同的报警等级 alarmLevels分类

        // 按不同的报警处理状态名称分类
        Map<String, List<AlarmEvent>> byHandelStatus = alarmEvents.stream()
                .collect(Collectors.groupingBy(AlarmEvent::getHandelStatus));

        // 对每个分类再按不同的报警等级分类
        Map<String, Map<String, List<AlarmEvent>>> byHandleAndAlarmLevel =
                byHandelStatus.entrySet().stream()
                        .collect(Collectors.toMap(
                                Map.Entry::getKey,
                                entry -> entry.getValue().stream()
                                        .collect(Collectors.groupingBy(AlarmEvent::getAlarmLevel))
                        ));






        //3.筛选出不同分类下 不同报警等级的次数
        Map<String, Map<String, Long>> alarmLevelCountMap = new HashMap<>();

        for (Map.Entry<String, List<AlarmEvent>> entry : alarmMap.entrySet()) {
            String categoryName = entry.getKey();
            List<AlarmEvent> events = entry.getValue();

            Map<String, Long> levelCountMap = new HashMap<>();
            String[] alarmLevels = {"5", "4", "3"};

            for (String level : alarmLevels) {
                levelCountMap.put(level, 0L);
            }

            for (AlarmEvent event : events) {
                String alarmLevel = event.getAlarmLevel();
                if (levelCountMap.containsKey(alarmLevel)) {
                    levelCountMap.put(alarmLevel, levelCountMap.get(alarmLevel) + 1);
                }
            }

            alarmLevelCountMap.put(categoryName, levelCountMap);
        }
        //4.查询监控点个数
        List<MonitorPoint> monitorPoints = statisticalAnalysisMapper.selectMonitorPointCountForUnitCodes(alarmEventRequest);

        //5.获取报警总数
        int alarmCount = alarmEvents.size();
        //3.获取监控点总数
        int monitorPointCount = monitorPoints.size();
        long l4=0;
        long l8=0;

        if(alarmLevelCountMap.get("1")!=null){

            long l = alarmLevelCountMap.get("1").get("5").longValue();
            long l2 = alarmLevelCountMap.get("1").get("4").longValue();
            long l3= alarmLevelCountMap.get("1").get("3").longValue();
            l4=l+l2+l3;
            ;;;        }
        if(alarmLevelCountMap.get("3")!=null){

            long l = alarmLevelCountMap.get("3").get("5").longValue();
            long l2 = alarmLevelCountMap.get("3").get("4").longValue();
            long l3= alarmLevelCountMap.get("3").get("3").longValue();
            l8=l+l2+l3
            ;;;        }

        result.put("conut1",l4);
        result.put("conut2",l8);
        result.put("alarmLevelSort",alarmLevelCountMap);
//        result.put("list",alarmMap);
        result.put("list",byHandleAndAlarmLevel);
        result.put("alarmCount",alarmCount);
        result.put("monitorPointCount",monitorPointCount);

        //https://console.huaweicloud.com/rds/?agencyId=ca5695528caa4036b7e6faf7dada890a&region=cn-north-4&locale=zh-cn#/rds/management/connectTab/838d3ccc2080453c8edd25a2815b4678in01


        return result;

    }


    @Override
    public Map<String,Object> selectAlarmIndexDemo(AlarmEventRequest alarmEventRequest) {

        Map<String, Object> result = new HashMap<>();
        //1.获取报警列表
        List<AlarmEvent> alarmEvents = statisticalAnalysisMapper.selectAlarmIndex(alarmEventRequest);
        List<String> urlListString = new ArrayList<>();
        for (AlarmEvent event : alarmEvents) {
            urlListString.add(event.getPictureUrl());
        }
//        if(urlListString.size()!=0){
//            String s = jyService.picAddrTrans(urlListString);
//            System.out.println(s);
//            Map<String, Object> maps = JSON.parseObject(s);
//            List<String> urlList2 = (List<String>) maps.get("data");
//            //遍历 List<AlarmEvent> alarmEvents 和 List<String> urlList2 依次按照数组索引 让 urlList2 的内容 代替 alarmEvents中的 pictureUrl 字段
//            if (alarmEvents.size() == urlList2.size()) {
//                for (int i = 0; i < alarmEvents.size(); i++) {
//                    AlarmEvent event = alarmEvents.get(i);
//                    String newPictureUrl = urlList2.get(i);
//                    System.out.println(newPictureUrl);
//                    event.setPictureUrl(newPictureUrl);
//                }
//            } else {
//                System.out.println("alarmEvents 和 urlList2 长度不一致！");
//            }
//            System.out.println(alarmEvents.get(0).getPictureUrl());
//        }
//        String s = jyService.picAddrTrans(urlListString);
//        System.out.println(s);
//        Map<String, Object> maps = JSON.parseObject(s);
//        List<String> urlList2 = (List<String>) maps.get("data");
//        //遍历 List<AlarmEvent> alarmEvents 和 List<String> urlList2 依次按照数组索引 让 urlList2 的内容 代替 alarmEvents中的 pictureUrl 字段
//        if (alarmEvents.size() == urlList2.size()) {
//            for (int i = 0; i < alarmEvents.size(); i++) {
//                AlarmEvent event = alarmEvents.get(i);
//                String newPictureUrl = urlList2.get(i);
//                System.out.println(newPictureUrl);
//                event.setPictureUrl(newPictureUrl);
//            }
//        } else {
//            System.out.println("alarmEvents 和 urlList2 长度不一致！");
//        }
//        System.out.println(alarmEvents.get(0).getPictureUrl());


        //2.按不同的报警事件名称 将list分类
        Map<String, List<AlarmEvent>> alarmMap2 = alarmEvents.stream()
                .collect(Collectors.groupingBy(AlarmEvent::getAlarmTypeName));

        //2.按不同的报警处理状态名称 将list分类
        Map<String, List<AlarmEvent>> alarmMap = alarmEvents.stream()
                .collect(Collectors.groupingBy(AlarmEvent::getHandelStatus));

        //List<AlarmEvent> alarmEvents 先按不同的报警处理状态名称 handelStatus将list分类 再按不同的报警等级 alarmLevels分类

        // 按不同的报警处理状态名称分类
        Map<String, List<AlarmEvent>> byHandelStatus = alarmEvents.stream()
                .collect(Collectors.groupingBy(AlarmEvent::getHandelStatus));

        // 对每个分类再按不同的报警等级分类
        Map<String, Map<String, List<AlarmEvent>>> byHandleAndAlarmLevel =
                byHandelStatus.entrySet().stream()
                        .collect(Collectors.toMap(
                                Map.Entry::getKey,
                                entry -> entry.getValue().stream()
                                        .collect(Collectors.groupingBy(AlarmEvent::getAlarmLevel))
                        ));

        // 打印按不同的报警处理状态名称分类和报警等级分类的结果
        System.out.println("按报警处理状态和报警等级分类：");
        for (Map.Entry<String, Map<String, List<AlarmEvent>>> entry : byHandleAndAlarmLevel.entrySet()) {
            String handleStatus = entry.getKey();
            Map<String, List<AlarmEvent>> byAlarmLevel = entry.getValue();
            System.out.println("处理状态：" + handleStatus);
            System.out.println("按报警等级分类的结果：");
            for (Map.Entry<String, List<AlarmEvent>> subEntry : byAlarmLevel.entrySet()) {
                String alarmLevel = subEntry.getKey();
                List<AlarmEvent> events = subEntry.getValue();
                System.out.println("报警等级：" + alarmLevel);
                System.out.println("对应的事件列表：");
                for (AlarmEvent event : events) {
                    System.out.println(event);
                }
                System.out.println();
            }
        }




        //3.筛选出不同分类下 不同报警等级的次数
        Map<String, Map<String, Long>> alarmLevelCountMap = new HashMap<>();

        for (Map.Entry<String, List<AlarmEvent>> entry : alarmMap.entrySet()) {
            String categoryName = entry.getKey();
            List<AlarmEvent> events = entry.getValue();

            Map<String, Long> levelCountMap = new HashMap<>();
            String[] alarmLevels = {"5", "4", "3"};

            for (String level : alarmLevels) {
                levelCountMap.put(level, 0L);
            }

            for (AlarmEvent event : events) {
                String alarmLevel = event.getAlarmLevel();
                if (levelCountMap.containsKey(alarmLevel)) {
                    levelCountMap.put(alarmLevel, levelCountMap.get(alarmLevel) + 1);
                }
            }

            alarmLevelCountMap.put(categoryName, levelCountMap);
        }
        //4.查询监控点个数
        List<MonitorPoint> monitorPoints = statisticalAnalysisMapper.selectMonitorPointCount(alarmEventRequest);

        //5.获取报警总数
        int alarmCount = alarmEvents.size();
        //3.获取监控点总数
        int monitorPointCount = monitorPoints.size();
        long l4=0;
        long l8=0;

        if(alarmLevelCountMap.get("1")!=null){

            long l = alarmLevelCountMap.get("1").get("5").longValue();
            long l2 = alarmLevelCountMap.get("1").get("4").longValue();
            long l3= alarmLevelCountMap.get("1").get("3").longValue();
            l4=l+l2+l3;
            ;;;        }
        if(alarmLevelCountMap.get("3")!=null){

            long l = alarmLevelCountMap.get("3").get("5").longValue();
            long l2 = alarmLevelCountMap.get("3").get("4").longValue();
            long l3= alarmLevelCountMap.get("3").get("3").longValue();
            l8=l+l2+l3
            ;;;        }

        result.put("conut1",l4);
        result.put("conut2",l8);
        result.put("alarmLevelSort",alarmLevelCountMap);
//        result.put("list",alarmMap);
        result.put("list",byHandleAndAlarmLevel);
        result.put("alarmCount",alarmCount);
        result.put("monitorPointCount",monitorPointCount);

        //https://console.huaweicloud.com/rds/?agencyId=ca5695528caa4036b7e6faf7dada890a&region=cn-north-4&locale=zh-cn#/rds/management/connectTab/838d3ccc2080453c8edd25a2815b4678in01


        return result;

    }


    @Override
    public List<String> mtlist(String apeName) {

        List<String> AllAlarmmaps = statisticalAnalysisMapper.mnlist(apeName);

        return AllAlarmmaps;
    }
    //

    @Override
    public Map<String,Object> selectDisplayIndex(AlarmEventRequest alarmEventRequest) {

        HashMap<String, Object> result = new HashMap<>();


        HashMap<String, Object> output = new HashMap<>();


        HashMap<Object, Object> salesMap = new HashMap<>();
        HashMap<Object, Object> outputMap = new HashMap<>();
        HashMap<Object, Object> powerMap = new HashMap<>();

//        ArrayList<String> timehHourList = new ArrayList<>();
        String[] timeHourList = getTimeHourList();
        Collections.reverse(Arrays.asList(timeHourList));
        String[] timehMonthList = getCurrentYearMonthArray();
        Collections.reverse(Arrays.asList(timehMonthList));
        HashMap<Object, Object> outputMonth = new HashMap<>();
        String[] weightHourList = getTimeHourListValue();
        List<String> timehDayList = getCurrentMonthDates();
        Collections.reverse(Arrays.asList(timehDayList));
        List<String> weightDayList = getCurrentMonthDatesValue();
        Collections.reverse(Arrays.asList(weightDayList));
        String[] currentYearMonthArrayValue = getCurrentYearMonthArrayValue();
        Collections.reverse(Arrays.asList(currentYearMonthArrayValue));
        outputMonth.put("outputMonth",6);

        outputMap.put("timehHourList",timeHourList);
        outputMap.put("timehMonthList",timehMonthList);
        outputMap.put("weightHourList",weightHourList);
        outputMap.put("timehDayList",timehDayList);
        outputMap.put("weightDayList",weightDayList);
        outputMap.put("weightMonthList",currentYearMonthArrayValue);
        outputMap.put("outputYear","931");
        outputMap.put("lastDayOverOutUnit","t");
        outputMap.put("outputDayUnit","t");
        outputMap.put("outputDay","2,026.141");
        outputMap.put("lastDayOverOut",0.0);
        outputMap.put("outputYearUnit","kt");
        outputMap.put("outputMonthUnit", "kt");

        output.put("outputMap",outputMap);
        output.put("salesMap",salesMap);
        output.put("powerMap",powerMap);
//        output.put()
        result.put("output",output);


        return result;

    }

    @Override
    public int InboundDataOftAlarm(Map map) {

        //Inbound data 入库数据
//        TAlarms tAlarm = JSON.parseObject(map.get("data").toString(),TAlarms.class);
        Map<String, Object> maps = JSON.parseObject(map.get("data").toString());

        HashMap<Object, Object> insertMap = new HashMap<>();

        String eventType = map.get("event_type").toString();
        insertMap.put("eventType",eventType);

        String eventId = map.get("event_id").toString();
        insertMap.put("eventId",eventId);

        String alarmLevel = maps.get("alarm_level").toString();
        insertMap.put("alarmLevel",alarmLevel);

        String alarmLevelName = maps.get("alarm_level_name").toString();
        insertMap.put("alarmLevelName",alarmLevelName);

        String alarmType = maps.get("alarm_type").toString();
        insertMap.put("alarmType",alarmType);

        String alarmTypeName = maps.get("alarm_type_name").toString();
        boolean hasPrefix = alarmTypeName.contains(namePrefix);
        boolean hasSuffix = alarmTypeName.contains(nameSuffix);

        if (hasPrefix && hasSuffix) {
            // 如果前缀和后缀都存在，则先截取前缀，再截取后缀
            int underscoreIndex = alarmTypeName.indexOf(namePrefix);
            if (underscoreIndex != -1) {
                alarmTypeName = alarmTypeName.substring(underscoreIndex + namePrefix.length());
                int endscoreIndex = alarmTypeName.indexOf(nameSuffix);
                if (endscoreIndex != -1) {
                    alarmTypeName = alarmTypeName.substring(0, endscoreIndex);
                }
            }
        } else if (hasPrefix) {
            // 如果只有前缀存在，则截取前缀后的字符串
            int underscoreIndex = alarmTypeName.indexOf(namePrefix);
            if (underscoreIndex != -1) {
                alarmTypeName = alarmTypeName.substring(underscoreIndex + namePrefix.length());
            }
        } else if (hasSuffix) {
            // 如果只有后缀存在，则截取后缀前的字符串
            int endscoreIndex = alarmTypeName.indexOf(nameSuffix);
            if (endscoreIndex != -1) {
                alarmTypeName = alarmTypeName.substring(0, endscoreIndex);
            }
        }

        insertMap.put("alarmTypeName", alarmTypeName);
        //
        //设备id 等于监控点 id
        String deviceId = maps.get("device_id").toString();
        insertMap.put("deviceId",deviceId);


        String deviceName = maps.get("device_name").toString();
        insertMap.put("deviceName",deviceName);

        String idStr = maps.get("id").toString();
        insertMap.put("idStr",idStr);

        String orgIndex = maps.get("org_index").toString();
        insertMap.put("orgIndex",orgIndex);

        String orgName = maps.get("org_name").toString();
        insertMap.put("orgName",orgName);

        String pictureUrl = maps.get("picture_url").toString();
        insertMap.put("pictureUrl",pictureUrl);

        Map<String, Object> bizJson = (Map<String, Object>) maps.get("biz_json");
        //设备名称 替换 orgName
        String puName = bizJson.get("pu_name").toString();
        insertMap.put("orgName",puName);


        String timeForStr = maps.get("alarm_time").toString();
        Long currentMilltimes = Long.valueOf(timeForStr);
        //报警时间获取
        String alarmTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(currentMilltimes);
        //获取报警时间

        insertMap.put("alarmTime",alarmTime);

        List<ReportApproval> reportApprovals = reportApprovalMapper.selectReportApprovalExists(insertMap);

        if(reportApprovals.size()>0){
            insertMap.put("filter","1");
        }

        //报警图片转http
        ArrayList<String> pictureUrlList = new ArrayList<>();
        pictureUrlList.add(pictureUrl);

        String s="";
        //当图片转化失败时 进行异常处理
        try {
            s = jyService.picAddrTrans(pictureUrlList);
        } catch (Exception e) {
            s = "";
        }

        Map<String, Object> Map = JSON.parseObject(s);
        if (Map==null||Map.get("data")==null){

        }else {
            List<String> urlList2 = (List<String>) Map.get("data");
            String newPictureUrl = urlList2.get(0);
            s=newPictureUrl;
        }
        insertMap.put("httpUrl",s);
        int i = alarmEventMapper.insertInboundDataOftAlarm(insertMap);
        if(i>0){
            boolean broadcastPlaySwitch = servletContext.getAttribute("broadcastPlaySwitch").equals(1);
            if(broadcastPlaySwitch==true){


                // 1. 获取监控点对应的广播设备ID数组
                List<BroadCast> broadCasts = broadcastMapper.selectMonitorAssociatedBroadcasts(deviceId);
                Integer[] ids = broadCasts.stream()
                        .map(BroadCast::getID) // 将 BroadCast 对象转换为 ID 值
                        .toArray(Integer[]::new);

            //2.广播播报（）仅播报一次
            BroadCastRequestVo broadCastRequestVo = new BroadCastRequestVo();
            broadCastRequestVo.setBroadcastContent(deviceName+alarmTypeName);
            broadCastRequestVo.setIds(ids);
            customConfigurationService.PlayBroadcastContent(broadCastRequestVo);

            }
        }

        return i;
    }

    @Override
    public int InboundDataOftAlarmForUnitCodes(Map map) {
        //Inbound data 入库数据
//        TAlarms tAlarm = JSON.parseObject(map.get("data").toString(),TAlarms.class);
        Map<String, Object> maps = JSON.parseObject(map.get("data").toString());


        HashMap<Object, Object> insertMap = new HashMap<>();
        //煤矿编码
        Long unitCode = (Long)map.get("unitCode");
        insertMap.put("unitCode",unitCode);
        //获取系统配置信息
        TUnitConfig tUnitConfigRequest = new TUnitConfig();
        tUnitConfigRequest.setUnitCode(unitCode);
        List<TUnitConfig> tUnitConfigs = iTUnitConfigService.selectTUnitConfigList(tUnitConfigRequest);
        TUnitConfig tUnitConfig = tUnitConfigs.get(0);
        String jyNamePrefix = tUnitConfig.getJyNamePrefix();
        String jyNameSuffix = tUnitConfig.getJyNameSuffix();

        if (jyNamePrefix!=null){
            namePrefix = tUnitConfig.getJyNamePrefix();
        }
        if (jyNameSuffix!=null){
            nameSuffix = tUnitConfig.getJyNameSuffix();
        }

        //事件类型
        String eventType = map.get("event_type").toString();
        insertMap.put("eventType",eventType);
        //事件ID
        String eventId = map.get("event_id").toString();
        insertMap.put("eventId",eventId);
        //告警级别
        String alarmLevel = maps.get("alarm_level").toString();
        insertMap.put("alarmLevel",alarmLevel);
        //告警级别名称
        String alarmLevelName = maps.get("alarm_level_name").toString();
        insertMap.put("alarmLevelName",alarmLevelName);
        //告警类型
        String alarmType = maps.get("alarm_type").toString();
        insertMap.put("alarmType",alarmType);

        String alarmTypeName = maps.get("alarm_type_name").toString();
        //
        boolean hasPrefix = alarmTypeName.contains(namePrefix);
        boolean hasSuffix = alarmTypeName.contains(nameSuffix);

        if (hasPrefix && hasSuffix) {
            // 如果前缀和后缀都存在，则先截取前缀，再截取后缀
            int underscoreIndex = alarmTypeName.indexOf(namePrefix);
            if (underscoreIndex != -1) {
                alarmTypeName = alarmTypeName.substring(underscoreIndex + namePrefix.length());
                int endscoreIndex = alarmTypeName.indexOf(nameSuffix);
                if (endscoreIndex != -1) {
                    alarmTypeName = alarmTypeName.substring(0, endscoreIndex);
                }
            }
        } else if (hasPrefix) {
            // 如果只有前缀存在，则截取前缀后的字符串
            int underscoreIndex = alarmTypeName.indexOf(namePrefix);
            if (underscoreIndex != -1) {
                alarmTypeName = alarmTypeName.substring(underscoreIndex + namePrefix.length());
            }
        } else if (hasSuffix) {
            // 如果只有后缀存在，则截取后缀前的字符串
            int endscoreIndex = alarmTypeName.indexOf(nameSuffix);
            if (endscoreIndex != -1) {
                alarmTypeName = alarmTypeName.substring(0, endscoreIndex);
            }
        }

        insertMap.put("alarmTypeName", alarmTypeName);
        //
        //设备id 等于监控点 id
        String deviceId = maps.get("device_id").toString();
        insertMap.put("deviceId",deviceId);


        String deviceName = maps.get("device_name").toString();
        insertMap.put("deviceName",deviceName);

        String idStr = maps.get("id").toString();
        insertMap.put("idStr",idStr);

        String orgIndex = maps.get("org_index").toString();
        insertMap.put("orgIndex",orgIndex);

        String orgName = maps.get("org_name").toString();
        insertMap.put("orgName",orgName);

        String pictureUrl = maps.get("picture_url").toString();
        insertMap.put("pictureUrl",pictureUrl);

        Map<String, Object> bizJson = (Map<String, Object>) maps.get("biz_json");
        //设备名称 替换 orgName
        String puName = bizJson.get("pu_name").toString();
        insertMap.put("orgName",puName);


        String timeForStr = maps.get("alarm_time").toString();
        Long currentMilltimes = Long.valueOf(timeForStr);
        //报警时间获取
        String alarmTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(currentMilltimes);
        //获取报警时间

        insertMap.put("alarmTime",alarmTime);

        List<ReportApproval> reportApprovals = reportApprovalMapper.selectReportApprovalExistsForUnitCode(alarmTime,deviceId,unitCode);

        if(reportApprovals.size()>0){
            insertMap.put("filter","1");
        }

        //报警图片转http
        ArrayList<String> pictureUrlList = new ArrayList<>();
        pictureUrlList.add(pictureUrl);


        String s="";
        //当图片转化失败时 进行异常处理
        System.out.println(LocalDateTime.now());
        try {
            s = jyService.picAddrTransForUnitCodes(pictureUrlList,tUnitConfig);
            /*
           s = http://172.16.129.236:11125/nginx-proxy?image_url=http://172.16.129.236:9003/?videolabel/dn@0_0/1/25-248a0778-a3aa0
            http://172.16.129.238:81/image/nginx-proxy?image_url=http://172.16.129.236:9003/?videolabel/dn@0_0/1/25-248a0778-a3aa0
            将s 从 //开始到11125 结束 进行替换 为 172:81
             */
            // 使用正则表达式进行替换
            String pattern = "//(.*?):11125";

            System.out.println("jyService.picAddrTransForUnitCodes"+s);
        } catch (Exception e) {
            s = "";
        }
        System.out.println(LocalDateTime.now());

        Map<String, Object> Map = JSON.parseObject(s);
        if (Map==null||Map.get("data")==null){

        }else {
            List<String> urlList2 = (List<String>) Map.get("data");
            String newPictureUrl = urlList2.get(0);
            s=newPictureUrl;
            //设置nginx代理前缀
            String nginxProxy = "http://"+SERVER_IP+":"+WEB_PORT+"/image_jy/";
            s= nginxProxy + s;
        }
        insertMap.put("httpUrl",s);
        int i = alarmEventMapper.insertInboundDataOftAlarm(insertMap);
        if(i>0){
            Integer broadcastSwitch = tUnitConfig.getBroadcastSwitch();
            if (tUnitConfig.getBroadcastSwitch()!=null && tUnitConfig.getBroadcastSwitch()==1){
                String broadcastIp = tUnitConfig.getBroadcastIp();

                //1. 获取监控点对应的广播设备ID数组
                List<BroadCast> broadCasts = broadcastMapper.selectMonitorAssociatedBroadcastsForUnitCodes(deviceId,unitCode);
                Integer[] ids = broadCasts.stream()
                        .map(BroadCast::getID) // 将 BroadCast 对象转换为 ID 值
                        .toArray(Integer[]::new);

                //2.广播播报（）仅播报一次
                BroadCastRequestVo broadCastRequestVo = new BroadCastRequestVo();
                broadCastRequestVo.setBroadcastContent(deviceName+alarmTypeName);
                broadCastRequestVo.setIds(ids);
                broadCastRequestVo.setUnitCode(unitCode);
                customConfigurationService.PlayBroadcastContentForUnitCodes(broadCastRequestVo);
            }
        }



        return i;
    }

    /**
     * 处理报警入库数据，并根据单位编码和设备ID检查是否存在报告审批记录，
     * 转换报警图片URL，并最终插入数据库。
     *
     * @param map 包含报警信息的映射对象
     * @return 插入数据库操作的结果，大于0表示成功，否则失败
     */
    @Override
    public int InboundDataOftAlarmForUnitCodesByOverlay(Map<String, Object> map) {
        // 解析传入的数据
        Map<String, Object> parsedData = JSON.parseObject(map.get("data").toString());

        // 获取单位编码
        Long unitCode = (Long) map.get("unitCode");

        // 获取单位配置信息
        TUnitConfig tUnitConfigRequest = new TUnitConfig();
        tUnitConfigRequest.setUnitCode(unitCode);
        List<TUnitConfig> tUnitConfigs = iTUnitConfigService.selectTUnitConfigList(tUnitConfigRequest);
        TUnitConfig tUnitConfig = tUnitConfigs.isEmpty() ? null : tUnitConfigs.get(0);

        // 准备插入数据库的数据
        HashMap<String, Object> insertMap = new HashMap<>();
        insertMap.put("unitCode", unitCode);
        insertMap.put("eventType", map.get("event_type"));
        insertMap.put("eventId", map.get("event_id"));
        insertMap.put("alarmLevel", parsedData.get("alarm_level"));
        insertMap.put("alarmLevelName", parsedData.get("alarm_level_name"));
        insertMap.put("alarmType", parsedData.get("alarm_type"));

        // 处理告警类型名称
        String alarmTypeName = processAlarmTypeName(parsedData, tUnitConfig);
        insertMap.put("alarmTypeName", alarmTypeName);

        // 设备ID等于监控点ID
        String deviceId = parsedData.get("device_id").toString();
        insertMap.put("deviceId", deviceId);

        // 其他字段
        insertMap.put("deviceName", parsedData.get("device_name"));
        insertMap.put("idStr", parsedData.get("id"));
        insertMap.put("orgIndex", parsedData.get("org_index"));
        insertMap.put("orgName", parsedData.get("org_name"));
        insertMap.put("pictureUrl", parsedData.get("picture_url"));

        // 格式化报警时间
        String alarmTime = formatAlarmTime(parsedData.get("alarm_time"));
        insertMap.put("alarmTime", alarmTime);

        // 检查是否存在报告审批记录
        List<ReportApproval> reportApprovals = reportApprovalMapper.selectReportApprovalExistsForUnitCode(alarmTime, deviceId, unitCode);
        if (!reportApprovals.isEmpty()) {
            insertMap.put("filter", "1");
        }

        // 转换图片URL
        String convertedImageUrl = convertImageUrl(parsedData, tUnitConfig);
        insertMap.put("httpUrl", convertedImageUrl);

        AlarmEventRequest alarmEventRequest = new AlarmEventRequest();
        alarmEventRequest.setUnitCode(unitCode);
        // 创建一个新的 ArrayList 并添加第一个元素
        List<String> deviceIds = new ArrayList<>();
        deviceIds.add(deviceId);
        alarmEventRequest.setApeIds(deviceIds);
        // 查询所有报警信息
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 解析字符串为 LocalDateTime
        LocalDateTime currentAlarmTime = LocalDateTime.parse(alarmTime, formatter);
        // 获取叠加秒数阈值
        Long overlaySeconds = (Long)map.get("OverlaySeconds");
        if (overlaySeconds==null){
            overlaySeconds = 300L;
        }
        LocalDateTime timeMinusFiveSeconds = currentAlarmTime.minusSeconds(overlaySeconds);
        // 将 LocalDateTime 转换为字符串
        String timeMinusFiveSecondsStr = timeMinusFiveSeconds.format(formatter);
        alarmEventRequest.setStartTime(timeMinusFiveSecondsStr);
        List<AlarmEvent> alarmEvents = statisticalAnalysisMapper.selectAllAlarmInfoV2(alarmEventRequest);
        if (alarmEvents !=null){
            //获取上一条告警记录
            AlarmEvent alarmEventLast = alarmEvents.get(0);
        }else {
        }

        // 执行数据库插入操作
        int result = alarmEventMapper.insertInboundDataOftAlarm(insertMap);

        // 返回操作结果
        return result;
    }

    /**
     * 处理告警类型名称，去除前缀后缀
     *
     * @param data 报警数据
     * @param config 单位配置信息
     * @return 处理后的告警类型名称
     */
    private String processAlarmTypeName(Map<String, Object> data, TUnitConfig config) {
        String alarmTypeName = (String) data.get("alarm_type_name");
        String namePrefix = config.getJyNamePrefix();
        String nameSuffix = config.getJyNameSuffix();

        if (namePrefix != null && alarmTypeName.startsWith(namePrefix)) {
            alarmTypeName = alarmTypeName.substring(namePrefix.length());
        }
        if (nameSuffix != null && alarmTypeName.endsWith(nameSuffix)) {
            alarmTypeName = alarmTypeName.substring(0, alarmTypeName.length() - nameSuffix.length());
        }
        return alarmTypeName;
    }

    /**
     * 格式化报警时间
     *
     * @param timeObj 时间对象
     * @return 格式化后的报警时间
     */
    private String formatAlarmTime(Object timeObj) {
        Long time = Long.valueOf(timeObj.toString());
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time);
    }

    /**
     * 转换图片URL
     *
     * @param data 报警数据
     * @param config 单位配置信息
     * @return 转换后的图片URL
     */
    private String convertImageUrl(Map<String, Object> data, TUnitConfig config) {
        String pictureUrl = (String) data.get("picture_url");
        String convertedUrl = "";

        try {
            List<String> pictureUrlList = Collections.singletonList(pictureUrl);
            String proxyResult = jyService.picAddrTransForUnitCodes(pictureUrlList, config);
            convertedUrl = "http://"+SERVER_IP+":"+WEB_PORT+"/image_jy/"+proxyResult;

        } catch (Exception e) {
            // 图片转换失败处理
        }
        return convertedUrl;
    }

    @Override
    public int InboundDataOftAlarmV2(Map map) {
        return 0;
    }

    public static String[] getTimeHourList() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH");
//        int second = now.getSecond();
        int currentHour = now.getHour();
        int currentDay = now.getDayOfYear();
        int currentYear = now.getYear();
        String[] timeHourList = new String[currentHour+1];
        for (int i = 0; i <= currentHour; i++) {

            timeHourList[i] = now.format(formatter);
            now = now.minusHours(1);
        }

        return timeHourList;
    }

    public static String[] getTimeHourListValue() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH");
        int currentHour = now.getHour();
        String[] timeHourList = new String[currentHour+1];
        for (int i = 0; i <= currentHour; i++) {
            int randomNumberByDate = getRandomNumberByDate(i,501);
            timeHourList[i] = String.valueOf(randomNumberByDate);
            now = now.minusHours(1);
        }

        return timeHourList;
    }

    /**
     *
     * 我返回前九个月月份数据
     * @return
     * @date 2023年10月29日 18时46分
     */
    public static String[] getCurrentYearMonthArray() {
        LocalDate now = LocalDate.now();
        String[] yearMonthArray = new String[9]; // 默认获取到目前的9个月份
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");

        for (int i = 0; i < 9; i++) { // 遍历9个月份
            yearMonthArray[i] = now.format(formatter);
            now = now.minusMonths(1);
        }

        return yearMonthArray;
//
    }

    /**
     *
     * 我返回前九个月月份数据
     * @return
     * @date 2023年10月29日 18时46分
     */
    public static String[] getCurrentYearMonthArrayValue() {
        LocalDate now = LocalDate.now();
        String[] yearMonthArray = new String[9]; // 默认获取到目前的9个月份
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");

        for (int i = 0; i < 9; i++) { // 遍历9个月份
            int randomNumberByDate = getRandomNumberByDate(i, 300);
            yearMonthArray[i] = String.valueOf(randomNumberByDate);
//            now = now.minusMonths(1);

        }

        return yearMonthArray;
//
    }

    /**
     *
     * 获取随机数
     * @param currentHour
     * @return
     * @date 2023年10月29日 18时29分
     */
    public static int getRandomNumberByDate(int currentHour,int max) {
//        LocalDate date = LocalDate.now(); // 获取当前日期
        Random random = new Random(currentHour);
        return random.nextInt(max); // 生成0到500之间的随机整数
    }

    /**
     *
     * 获取当前月份包含今天的日期 格式为  "yyyy-MM-dd"
     * @return
     * @date 2023年10月29日 18时30分
     */
    public static List<String> getCurrentMonthDates() {
        LocalDate currentDate = LocalDate.now();
        int currentDayOfMonth = currentDate.getDayOfMonth();
        List<String> dateArray = new ArrayList<>();

        for (int i = 1; i <= currentDayOfMonth; i++) {
            String date = currentDate.withDayOfMonth(i).format(DateTimeFormatter.ISO_DATE);
            dateArray.add(date);
        }

        return dateArray;
    }

    /**
     *
     * 获取当前月份包含今天的日期 格式为  "yyyy-MM-dd"
     * @return
     * @date 2023年10月29日 18时30分
     */
    public static List<String> getCurrentMonthDatesValue() {
        LocalDate currentDate = LocalDate.now();
        int currentDayOfMonth = currentDate.getDayOfMonth();
        List<String> dateArray = new ArrayList<>();

        for (int i = 1; i <= currentDayOfMonth; i++) {

            int randomNumberByDate = getRandomNumberByDate(i, 10);
            dateArray.add(String.valueOf(randomNumberByDate));
        }

        return dateArray;
    }

    private boolean isBetween(LocalDateTime time, LocalDateTime start, LocalDateTime end) {
        return (time.isAfter(start) || time.isEqual(start)) && time.isBefore(end);
    }


}
